package com.huanf.controller;

import cn.hutool.core.date.DateUtil;
import com.huanf.domain.dto.WxMessageDto;
import com.huanf.domain.pojo.Article;
import com.thoughtworks.xstream.XStream;
import org.dom4j.Document;
import org.dom4j.DocumentException;
import org.dom4j.Element;
import org.dom4j.io.SAXReader;
import org.springframework.web.bind.annotation.*;

import javax.servlet.ServletInputStream;
import javax.servlet.http.HttpServletRequest;
import java.io.IOException;
import java.util.*;

import static com.huanf.utils.MyWxUtil.SHA1;

@RestController
public class WxController {

    private static final String TOKEN = "huanfqc"; // 替换为你的token

    /**
     * https://mp.weixin.qq.com 设置与开发->基本配置->服务器配置->接入微信开发平台
     * @param signature
     * @param timestamp
     * @param nonce
     * @param echostr
     * @return
     */
    @GetMapping("/")
    public String checkSignature(@RequestParam("signature") String signature,
                                 @RequestParam("timestamp") String timestamp,
                                 @RequestParam("nonce") String nonce,
                                 @RequestParam("echostr") String echostr) {
        String[] arr = {TOKEN, timestamp, nonce};
        Arrays.sort(arr);
        StringBuilder sb = new StringBuilder();
        for (String s : arr) {
            sb.append(s);
        }
        String tmpStr = SHA1(sb.toString());

        if (tmpStr.equals(signature)) {
            return echostr;
        } else {
            return "签名不匹配";
        }
    }

    //接收来自微信服务器的xml格式消息
    @PostMapping("/")
    public String receiveMessage(HttpServletRequest request) throws IOException {
        ServletInputStream inputStream = request.getInputStream();
        HashMap<String, String> map = new HashMap<>();
        SAXReader reader = new SAXReader();
        try {
            Document document = reader.read(inputStream);
            Element root  = document.getRootElement();
            List<Element> elements = root.elements();
            for (Element element : elements) {
                map.put(element.getName(), element.getStringValue());
            }
        } catch (DocumentException e) {
            e.printStackTrace();
        }
        //回复哪种消息给用户
        String message = getReplyMessage(map);
        //String message = getReplyNewsMessage(map);
        System.out.println(map);
        return message;
    }

    /**
     * 回复图文信息给用户
     * @param map
     * @return
     */
    private String getReplyNewsMessage(Map<String, String> map) {
        WxMessageDto messageDto = new WxMessageDto();
        messageDto.setToUserName(map.get("FromUserName"));
        messageDto.setFromUserName(map.get("ToUserName"));
        messageDto.setMsgType("news");
        messageDto.setCreateTime(System.currentTimeMillis());
        messageDto.setArticleCount(1L);//表示里面只有一个item

        List<Article> articles = new ArrayList<>();
        Article article = new Article();
        article.setTitle("我是图文标题");
        article.setDescription("我是图文描述。当用户发送消息给公众号时，会产生一个POST请求，开发者可以在响应包（Get）中返回特定XML结构，来对该消息进行响应");
        article.setUrl("https://huanf.top");
        article.setPicUrl("https://www.huanf.top//2024/02/04/b7d2dc6fcb4c48d28ab2138696411877.png");
        articles.add(article);
        messageDto.setArticles(articles);

        XStream xStream = new XStream();
        xStream.processAnnotations(WxMessageDto.class);
        String xml = xStream.toXML(messageDto);
        return xml;
    }

    /**
     * 回复文本消息给用户
     * @param map
     * @return
     */
    private String getReplyMessage(HashMap<String, String> map) {
        WxMessageDto messageDto = new WxMessageDto();
        messageDto.setToUserName(map.get("FromUserName"));
        messageDto.setFromUserName(map.get("ToUserName"));
        messageDto.setMsgType(map.get("MsgType").equals("text") ? "text" : "text");//用户问我们什么类型，我们就回复什么类型。暂时先统一回复文本类型
        //用户问什么就回答什么
        String input = map.get("Content");
        if ("1".equals(input)) {
            StringBuilder content = new StringBuilder();
            content.append("微信公众号后台\n");
            content.append("https://mp.weixin.qq.com\n");
            content.append("\n");
            content.append("邮箱 huanfqc@163.com\n");
            content.append("\n");
            content.append("开发文档\n");
            content.append("https://developers.weixin.qq.com/doc/offiaccount/");
            content.append("User_Management/Gets_a_users_location.html\n");
            content.append("\n");
            content.append("AppID\n");
            content.append("wx5ddd2cb0d41c1986\n");
            content.append("\n");
            content.append("AppSecret\n");
            content.append("af3b314a24cc4acd455817f7676072f9");
            messageDto.setContent(content.toString());
        } else if ("2".equals(input)) {
            StringBuilder content = new StringBuilder();
            content.append("测试号管理\n");
            content.append("https://mp.weixin.qq.com/debug/cgi-bin/sandboxinfo?");
            content.append("action=showinfo&t=sandbox/index\n");
            content.append("\n");
            content.append("🌐微信账号扫码登录\n");
            content.append("\n");
            content.append("appID\n");
            content.append("wx8ad0fc185904866f\n");
            content.append("\n");
            content.append("appsecret\n");
            content.append("ba133089bc3dfcdabe555a94ac34c302");
            messageDto.setContent(content.toString());
        } else if ("3".equals(input)) {
            StringBuilder content = new StringBuilder();
            content.append("官网 https://www.ngrok.cc\n");
            content.append("邮箱 huanfqc@163.com\n");
            content.append("域名 http://huanfqc.v1.idcfengye.com\n");
            content.append("隧道 081456422570\n");
            content.append("端口 8830");
            messageDto.setContent(content.toString());
        } else if ("图文".equals(input)) {
            messageDto.setToUserName(map.get("FromUserName"));
            messageDto.setFromUserName(map.get("ToUserName"));
            messageDto.setMsgType("news");
            messageDto.setCreateTime(System.currentTimeMillis());
            messageDto.setArticleCount(1L);//表示里面只有一个item

            List<Article> articles = new ArrayList<>();
            Article article = new Article();
            article.setTitle("我是图文标题");
            article.setDescription("我是图文描述。当用户发送消息给公众号时，会产生一个POST请求，开发者可以在响应包（Get）中返回特定XML结构，来对该消息进行响应");
            article.setUrl("https://huanf.top");
            article.setPicUrl("https://www.huanf.top//2024/02/04/b7d2dc6fcb4c48d28ab2138696411877.png");
            articles.add(article);
            messageDto.setArticles(articles);
        } else {
            StringBuilder content = new StringBuilder();
            content.append("欢迎关注huanfqc公众号，请回复如下数字获取更多~~\n");
            content.append("回复 1 领取微信公众号后台地址链接\n");
            content.append("回复 2 领取测试号地址链接\n");
            content.append("回复 3 领取ngrok地址链接\n");
            content.append("回复 图文 领取图文地址链接\n\n");
            content.append("当前时间: "+DateUtil.now());
            messageDto.setContent(content.toString());
        }
        messageDto.setCreateTime(System.currentTimeMillis());

        XStream xStream = new XStream();
        xStream.processAnnotations(WxMessageDto.class);
        String xml = xStream.toXML(messageDto);
        return xml;
    }
}
